<?php

namespace App\Http\Controllers\Api;

use App\Models\Site;
use QL\QueryList;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

class RankController extends Controller
{
    //
    public function search($id)
    {
        $site    = Site::where('id', $id)->first();

        $pr     = $this->pr($site->url);
        $rank   = $this->rank($site->url);
        $alexa  = $this->alexa($site->url);
        $ip     = [
            'ip'    => gethostbyname($site->url)
        ];
        if(is_array($pr) and is_array($rank) and is_array($alexa)) {
            $array      = array_merge($pr,$rank,$ip,$alexa);
            $flight = Site::find($id);
            $flight->content = $array;
            $flight->save();
            $this->ziyuan($id);
            return response()->json(['msg' => '数据已经获取成功!3秒后,刷新页面', 'code' => '0'],200);
        }
        return response()->json(['msg' => '您需要的数据!出现问题,正在修理过程中……请稍候重试!……', 'code' => '1'],200);
    }
    public function pr($name)
    {
        $pr = $this->check('https://pr.aizhan.com/'.$name.'/');
        if(!$pr) {
            return [
                'br'  => 0,
                'mbr'  => 0,
            ];
        }
        $ql = QueryList::html($pr)->rules([
            //采集规则
            'pr'    => ['img:eq(0)','alt'],
            'sbr'    => ['img:eq(1)','alt'],
        ])->range('.pr-content')->query()->getData();
        $data   = $ql->all();
        if(array_key_exists(0,$data)){
            return [
                'pr'  => $data[0]['pr'],
                'sbr'  => $data[0]['sbr'],
            ];
        }else{
            return [
                'br'  => 0,
                'mbr'  => 0,
            ];
        }
    }
    public function rank($name)
    {
        $pr = $this->check('https://baidurank.aizhan.com/baidu/'.$name);
        if(!$pr) {
            return [
                'br'  => 0,
                'mbr'  => 0,
            ];
        }
        $ql = QueryList::html($pr)->rules([
            //采集规则
            'br'    => ['img:eq(0)','src'],
            'mbr'    => ['img:eq(1)','src'],
        ])->range('.baidurank-infos')->query()->getData(function ($item){
            $item['br']     = basename($item['br'],".png");
            $item['mbr']    = basename($item['mbr'],".png");
            return $item;
        });
        $data   = $ql->all();
        if(array_key_exists(0,$data)){
            return [
                'br'  => $data[0]['br'],
                'mbr'  => $data[0]['mbr'],
            ];
        }else{
            return [
                'br'  => 0,
                'mbr'  => 0,
            ];
        }
    }
    public function alexa($name)
    {
        $chinaz = $this->check('https://www.aizhan.com/cha/'.$name.'/');
        if(!$chinaz) {
            return false;
        }
        $ql = QueryList::html($chinaz)->rules([
            //采集规则
            'first'  => ['li:eq(0)','text'],
            'rank'    => ['li:eq(0)>#alexa_rank','text'],
            'html'    => ['li','html'],
        ])->range('#alexa')->query()->getData(function ($item){
            if($item['first'] == '暂无排名或相关数据不充分'){
                $item['num']    = 0;
            }else{
                $item['num']    = $item['rank'];
            }
            return $item;
        });
        $data   = $ql->all();
        if(array_key_exists(0,$data)){
            return [
                'alexa'      => $data[0]['num'],
            ];
        }else{
            return [
                'alexa'      => 0,
            ];
        }
    }
    //抓取网址
    function check($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);//抓取网址
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Baiduspider/3.0; +http://www.baidu.com/search/spider.html)");//伪造百度蜘蛛头部
        $ip = '220.181.7.121';
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:' . $ip, 'CLIENT-IP:' . $ip));//伪造百度蜘蛛IP
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//
//        curl_setopt($ch, CURLOPT_HEADER, true); //抓取服务器信息
        curl_setopt($ch, CURLOPT_NOBODY, false); //抓取网页信息
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //支持301跳转
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 30); //网页等待时间
        $data = curl_exec($ch);
        $code = curl_getinfo($ch);
        curl_close($ch);
        if($code['http_code'] == 200){
            return $data;
//            $parse_url  = parse_url($code['url']);
//            return      $parse_url['scheme'].'://'.$parse_url['host'];
        }else{
            return false;
        }
    }
    
    function ziyuan($id)
    {
        $urls = array(
            env('APP_URL').'/siteinfo-'.$id.'.html',
        );
        $api = env('BAIDUZHANZHANG');
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        return $result;
    }
}
